package com.swk.form;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.servlet.http.HttpServletRequest;

import sun.misc.BASE64Encoder;

/**
 * 令牌帮助类，产生验证随机数，单例模式
 */
public class TokenUtils {

	private TokenUtils() {}
	
	public static final TokenUtils instance = new TokenUtils();
	
	public static TokenUtils getInstance(){
		return instance;
	}
	
	/**
	 * 产生随机数的方法
	 */
	public String generateToken() {
		// 一个伪随机数加系统当前毫秒值生成随机数
		String token = new Random().nextInt(999999) + "" + System.currentTimeMillis();
		//MD5 数据摘要
		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] md5 = md.digest(token.getBytes());
			
			//base64
			BASE64Encoder encoder = new BASE64Encoder();
			return encoder.encode(md5);
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException(e);
		}
	}
	
    /**
     * 判断用户的令牌是否有效
     * @param request
     * @return
     */
	public boolean isToken(HttpServletRequest request) {
		//取得客户端token及服务器的token
		String client_token = request.getParameter("token");
		String server_token = (String) request.getSession().getAttribute("token");
		
		//校验
		if(client_token==null){//外部表单
			return false;
		}
		
		if(server_token==null){//已经提交过了
			return false;
		}
//		System.out.println("client_token-->" + client_token);
//		System.out.println("server_token-->" + server_token);
		if(!server_token.equals(client_token)){
			return false;
		}
		return true;
	}
	
}
